//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from "react";
import type { RequirementInfo } from "@/api/project_requirement";
import { get_requirement, update_requirement, open_requirement, close_requirement, remove_requirement } from "@/api/project_requirement";
import { Button, Card, Form, Modal, Popover, Space } from "antd";
import { request } from "@/utils/request";
import { EditText } from "@/components/EditCell/EditText";
import { ReadOnlyEditor, useCommonEditor } from "@/components/Editor";
import { FILE_OWNER_TYPE_REQUIRE_MENT } from "@/api/fs";
import { EditTag } from "@/components/EditCell/EditTag";
import { MoreOutlined } from "@ant-design/icons";
import type { ProjectInfo, TagInfo } from "@/api/project";
import { get_session } from "@/api/user";
import ShareSvg from '@/assets/svg/share.svg?react';
import { type GetCfgResponse, type VendorConfig, get_cfg, report_error, get_vendor_config } from "@/api/client_cfg";
import ShareModal from '@/pages/Project/Share/ShareModal';
import { SHARE_TARGET_REQUIRE_MENT } from "@/api/project_share";


export interface DetailPanelProps {
    projectInfo: ProjectInfo;
    myUserId: string;
    tagList: TagInfo[];
    requirementId: string;
    onClose: () => void;
}

const DetailPanel = (props: DetailPanelProps) => {
    const [reqInfo, setReqInfo] = useState<RequirementInfo | null>(null);
    const [inEditContent, setInEditContent] = useState(false);
    const [showRemoveModal, setShowRemoveModal] = useState(false);
    const [showShareModal, setShowShareModal] = useState(false);

    const [clientCfg, setClientCfg] = useState<GetCfgResponse | null>(null);
    const [vendorCfg, setVendorCfg] = useState<VendorConfig | null>(null);


    const { editor, editorRef } = useCommonEditor({
        content: "",
        fsId: props.projectInfo.require_ment_fs_id,
        ownerType: FILE_OWNER_TYPE_REQUIRE_MENT,
        ownerId: props.requirementId,
        historyInToolbar: false,
        clipboardInToolbar: false,
        commonInToolbar: true,
        pubResInToolbar: false,
        placeholder: "请输入需求...",
    });

    const loadClientCfg = async () => {
        const res = await get_cfg();
        setClientCfg(res);
    };

    const loadVendorCfg = async () =>{
        const res = await get_vendor_config();
        setVendorCfg(res);
    };

    const loadReqInfo = async () => {
        const sessionId = await get_session();
        const res = await request(get_requirement({
            session_id: sessionId,
            project_id: props.projectInfo.project_id,
            requirement_id: props.requirementId,
        }));
        setReqInfo(res.requirement);
    };

    const updateContent = async () => {
        const sessionId = await get_session();
        if (editorRef.current == null) {
            return;
        }
        if (reqInfo == null) {
            return;
        }
        const content = editorRef.current.getContent();
        await request(update_requirement({
            session_id: sessionId,
            project_id: props.projectInfo.project_id,
            requirement_id: props.requirementId,
            base_info: {
                title: reqInfo.base_info.title,
                content: JSON.stringify(content),
                tag_id_list: reqInfo.base_info.tag_id_list,
            },
        }));
        setReqInfo(oldValue => {
            if (oldValue != null) {
                oldValue.base_info.content = JSON.stringify(content);
            }
            return oldValue;
        });
        setInEditContent(false);
    };

    const updateTagIdList = async (tagIdList: string[]) => {
        const sessionId = await get_session();
        if (reqInfo == null) {
            return;
        }
        await request(update_requirement({
            session_id: sessionId,
            project_id: props.projectInfo.project_id,
            requirement_id: props.requirementId,
            base_info: {
                title: reqInfo.base_info.title,
                content: reqInfo.base_info.content,
                tag_id_list: tagIdList,
            },
        }));
        setReqInfo(oldValue => {
            if (oldValue != null) {
                oldValue.base_info.tag_id_list = tagIdList;
            }
            return oldValue;
        });
    };

    const removeRequirement = async () => {
        const sessionId = await get_session();
        await request(remove_requirement({
            session_id: sessionId,
            project_id: props.projectInfo.project_id,
            requirement_id: props.requirementId,
        }));
        setShowRemoveModal(false);
        props.onClose();
    };

    useEffect(() => {
        loadReqInfo();
    }, [props.requirementId]);

    useEffect(() => {
        loadClientCfg();
        loadVendorCfg();
    }, []);

    return (
        <div>
            {reqInfo != null && (
                <>
                    <Card title={
                        <>
                            <span style={{ fontSize: "16px", fontWeight: 600 }}>标题:&nbsp;</span>
                            <EditText editable={reqInfo.user_requirement_perm.can_update} content={reqInfo.base_info.title} showEditIcon
                                fontSize="16px" fontWeight={600}
                                onChange={async value => {
                                    if (value.trim() == "") {
                                        return false;
                                    }
                                    try {
                                        const sessionId = await get_session();
                                        await request(update_requirement({
                                            session_id: sessionId,
                                            project_id: props.projectInfo.project_id,
                                            requirement_id: props.requirementId,
                                            base_info: {
                                                title: value.trim(),
                                                content: reqInfo.base_info.content,
                                                tag_id_list: reqInfo.base_info.tag_id_list,
                                            },
                                        }));
                                        setReqInfo(oldValue => {
                                            if (oldValue != null) {
                                                oldValue.base_info.title = value.trim();
                                            }
                                            return oldValue;
                                        });
                                        return true;
                                    } catch (e) {
                                        console.log(e);
                                        report_error({
                                            err_data: `${e}`,
                                        });
                                        return false;
                                    }
                                }}
                            />
                        </>
                    }
                        headStyle={{ padding: "0px 10px" }} bordered={false}
                        extra={
                            <Space>
                                {vendorCfg != null && vendorCfg.project.enable_share && clientCfg != null && clientCfg.share_web_url != "" && inEditContent == false && (
                                    <Button type="text" icon={<ShareSvg style={{ width: "20px", height: "20px", color: "#777" }} />}
                                        onClick={e => {
                                            e.stopPropagation();
                                            e.preventDefault();
                                            setShowShareModal(true);
                                        }} />
                                )}
                                {inEditContent == false && reqInfo.user_requirement_perm.can_update && (
                                    <Button type="primary" onClick={e => {
                                        e.stopPropagation();
                                        e.preventDefault();
                                        setInEditContent(true);
                                        const t = setInterval(() => {
                                            if (editorRef.current != null) {
                                                editorRef.current.setContent(reqInfo.base_info.content);
                                                clearInterval(t);
                                            }
                                        }, 100);
                                    }}>编辑内容</Button>
                                )}
                                {inEditContent == false && (
                                    <Popover trigger="click" placement="bottom" content={
                                        <Space direction="vertical" style={{ padding: "10px 10px" }}>
                                            {reqInfo.user_requirement_perm.can_open && (
                                                <Button type="link" onClick={e => {
                                                    e.stopPropagation();
                                                    e.preventDefault();
                                                    const f = async () => {
                                                        const sessionId = await get_session();
                                                        await request(open_requirement({
                                                            session_id: sessionId,
                                                            project_id: props.projectInfo.project_id,
                                                            requirement_id: props.requirementId,
                                                        }));
                                                        await loadReqInfo();
                                                    };
                                                    f();
                                                }}>打开需求</Button>
                                            )}
                                            {reqInfo.user_requirement_perm.can_close && (
                                                <Button type="link" onClick={e => {
                                                    e.stopPropagation();
                                                    e.preventDefault();
                                                    const f = async () => {
                                                        const sessionId = await get_session();
                                                        await request(close_requirement({
                                                            session_id: sessionId,
                                                            project_id: props.projectInfo.project_id,
                                                            requirement_id: props.requirementId,
                                                        }));
                                                        await loadReqInfo();
                                                    };
                                                    f();
                                                }}>关闭需求</Button>
                                            )}
                                            <Button type="link" danger disabled={!reqInfo.user_requirement_perm.can_remove}
                                                onClick={e => {
                                                    e.stopPropagation();
                                                    e.preventDefault();
                                                    setShowRemoveModal(true);
                                                }}>移至回收站</Button>
                                        </Space>
                                    }>
                                        <MoreOutlined />
                                    </Popover>
                                )}
                                {inEditContent == true && (
                                    <>
                                        <Button onClick={e => {
                                            e.stopPropagation();
                                            e.preventDefault();
                                            setInEditContent(false);
                                        }}>取消</Button>
                                        <Button type="primary" onClick={e => {
                                            e.stopPropagation();
                                            e.preventDefault();
                                            updateContent();
                                        }}>保存</Button>
                                    </>
                                )}
                            </Space>
                        }>
                        {inEditContent == false && (
                            <div className="_chatContext">
                                <ReadOnlyEditor content={reqInfo.base_info.content} />
                            </div>
                        )}
                        {inEditContent == true && (
                            <div className="_chatContext">
                                {editor}
                            </div>
                        )}
                    </Card>
                    <Card title={<span style={{ fontSize: "16px", fontWeight: 600 }}>其他配置</span>} headStyle={{ padding: "0px 10px" }} bordered={false} >
                        <Form>
                            <Form.Item label="标签">
                                <EditTag editable={reqInfo.user_requirement_perm.can_update} tagIdList={reqInfo.base_info.tag_id_list}
                                    tagDefList={props.tagList.filter(item => item.use_in_req)}
                                    onChange={tagIdList => updateTagIdList(tagIdList)} />
                            </Form.Item>
                        </Form>
                    </Card>
                    {showRemoveModal == true && (
                        <Modal open title="移至回收站" mask={false}
                            okText="移至" okButtonProps={{ danger: true }}
                            onCancel={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                setShowRemoveModal(false);
                            }}
                            onOk={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                removeRequirement();
                            }}>
                            是否把项目需求&nbsp;{reqInfo.base_info.title}&nbsp;移至回收站?
                        </Modal>
                    )}
                    {showShareModal == true && clientCfg != null && reqInfo != null && (
                        <ShareModal projectInfo={props.projectInfo} myUserId={props.myUserId}
                            shareTargetId={props.requirementId} shareTargetType={SHARE_TARGET_REQUIRE_MENT}
                            shareTitle={reqInfo.base_info.title} shareWebUrl={clientCfg.share_web_url ?? ""}
                            timeDiff={(clientCfg?.server_time ?? 0) - (clientCfg?.client_time ?? 0)}
                            onClose={() => setShowShareModal(false)} />
                    )}
                </>
            )}
        </div>
    )
};

export default DetailPanel;